package me.aartikov.screenresultsample;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import me.aartikov.alligator.*;
import me.aartikov.alligator.helpers.BaseAbility;
import me.aartikov.alligator.annotations.RegisterScreen;
import me.aartikov.alligator.listeners.ScreenResultListener;
import me.aartikov.alligator.util.Toast;
import me.aartikov.screenresultsample.screens.ImagePickerScreen;
import me.aartikov.screenresultsample.screens.MainScreen;
import me.aartikov.screenresultsample.screens.MessageInputScreen;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.agp.components.TableLayout;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.bundle.IBundleManager;
import ohos.utils.net.Uri;

@RegisterScreen(MainScreen.class)
public class MainAbility extends BaseAbility implements ScreenResultListener {
    private Navigator mNavigator;
    private NavigationContextBinder mNavigationContextBinder;
    private AbilityResultHandler mActivityResultHandler;

    Button inputMessageButton;
    Button pickImageButton;
    Text messageTextView;
    Image imageView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mNavigator = SampleApplication.getNavigator();
        mNavigationContextBinder = SampleApplication.getNavigationContextBinder();
        mActivityResultHandler = SampleApplication.getActivityResultHandler();
        initView();
    }


    public void checkPromission() {
        if (verifySelfPermission("ohos.permission.READ_MEDIA") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.READ_MEDIA")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                        new String[]{"ohos.permission.READ_MEDIA"}, 100);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
                Toast.show(this, "当前未获取到读取相册的权限,请进入设置中进行设置");
            }
        } else {
            // 权限已被授予
            mNavigator.goForward(new ImagePickerScreen());
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100: {
                // 匹配requestPermissions的requestCode
                if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                    mNavigator.goForward(new ImagePickerScreen());
                } else {
                    // 权限被拒绝
                    Toast.show(this, "获取到读取相册的权限被拒绝,请进入设置中进行设置");
                }
                return;
            }
        }
    }

    private void initView() {
        messageTextView = (Text) findComponentById(ResourceTable.Id_message_text_view);
        imageView = (Image) findComponentById(ResourceTable.Id_image_view);
        inputMessageButton = (Button) findComponentById(ResourceTable.Id_input_message_button);
        pickImageButton = (Button) findComponentById(ResourceTable.Id_pick_image_button);

        inputMessageButton.setClickedListener(v -> mNavigator.goForward(new MessageInputScreen()));
        pickImageButton.setClickedListener(v -> checkPromission());
    }

    private void onMessageInputted(MessageInputScreen.Result messageInputResult) {
        messageTextView.setText(getString(ResourceTable.String_inputted_message_template, messageInputResult.getMessage()));
    }

    private void onImagePicked(ImagePickerScreen.Result imagePickerResult) {
        String s = imagePickerResult.getUri().toString().replace("content:", "dataability:/");
        Glide.with(this)
                .load(Uri.parse(s))
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(imageView);
    }

    @Override
    protected void onActive() {
        super.onActive();
        NavigationContext navigationContext = new NavigationContext.Builder(this, SampleApplication.getNavigationFactory())
                .screenResultListener(this)      // set ScreenResultListener
                .build();
        mNavigationContextBinder.bind(navigationContext);
    }

    @Override
    public void onScreenResult(Class<? extends Screen> screenClass, ScreenResult result) {

        if (result == null) {
            Toast.show(this, getString(ResourceTable.String_cancelled), Toast.ToastLayout.BOTTOM);
            return;
        }

        if (result instanceof MessageInputScreen.Result) {
            onMessageInputted((MessageInputScreen.Result) result);
        } else if (result instanceof ImagePickerScreen.Result) {
            onImagePicked((ImagePickerScreen.Result) result);
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        mActivityResultHandler.onActivityResult(requestCode, resultCode, resultData);     // handle result
    }

    @Override
    protected void onInactive() {
        mNavigationContextBinder.unbind(this);
        super.onInactive();
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
//        mNavigator.goBack();
    }

}
